﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;

namespace Demo.Controllers
{
    public static class ObjectExtensions
    {
        public static ExpandoObject shapeData<TSource>(this TSource source, string fields)
        {
            if (fields == null) throw new ArgumentNullException(nameof(fields));

            var sourceProperties =
                typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);

            if (!string.IsNullOrWhiteSpace(fields))
            {
                var fieldsArr = fields.Split(',', StringSplitOptions.RemoveEmptyEntries);

                sourceProperties = sourceProperties.Where(x => fieldsArr.Contains(x.Name)).ToArray();
            }

            var expandoObj = new ExpandoObject();

            foreach (var propertyInfo in sourceProperties)
            {
                ((IDictionary<string, object>) expandoObj).Add(propertyInfo.Name, propertyInfo.GetValue(source));
            }

            return expandoObj;
        }
    }
}